SET SESSION FOREIGN_KEY_CHECKS=0;

/* Drop Tables */
DROP TABLE IF EXISTS ${dbTableName};

/* Create Tables */

<#assign hasPrimary = false >
<#assign hasUnique = false >
<#assign fieldSize = (tableFields?size)!0>
<#assign uniqueFieldSize = 0 >
<#list tableFields as field>
<#if field.unique?? && field.unique>
	<#assign hasUnique = true >
	<#assign uniqueFieldSize = uniqueFieldSize + 1 >
</#if>
<#if field.pk?? && field.pk>
	<#assign hasPrimary = true>
</#if>
</#list>

-- ${tableDesc}
CREATE TABLE ${dbTableName}
(
	<#list tableFields as field>
	-- ${field.desc}
	${field.name} ${field.type}<#if field.length?? && field.length gt 0>(${field.length}<#if field.decimal?? && field.decimal gt 0>,${field.decimal}</#if>)</#if> <#if !field.nullable>NOT NULL </#if><#if field.defaultVal??>DEFAULT '${field.defaultVal}' </#if><#if field.autoIncable?? && field.autoIncable>AUTO_INCREMENT </#if>COMMENT '${field.desc}'<#if hasUnique || hasPrimary || field_index lt (fieldSize-1)>,</#if>
	</#list>
	<#if primaryKeys??>
	PRIMARY KEY (${(primaryKeys)!''})<#if hasUnique>,</#if>
	<#assign hasPrimary = true >
	</#if>
	<#assign curUniqueIndex = 0>
	<#list tableFields as field>
	<#if field.unique?? && field.unique>
	<#assign curUniqueIndex = curUniqueIndex +1>
	UNIQUE (${field.name})<#if curUniqueIndex != uniqueFieldSize>,</#if>
	</#if>
	</#list>
) COMMENT = '${tableDesc}';